<template>
    <div class="table-generator-container">
        <el-row :gutter="20">
            <el-col :span="12">
                <el-card class="box-card" header="列表配置">
                    <el-form :model="tableConfig" label-width="140px">
                        <el-form-item label="列表标题">
                            <el-input v-model="tableConfig.title"></el-input>
                        </el-form-item>
                        <el-form-item label="是否筛选">
                            <el-switch v-model="tableConfig.isFilter"></el-switch>
                        </el-form-item>
                        <el-form-item label="是否分页">
                            <el-switch v-model="tableConfig.pagination"></el-switch>
                        </el-form-item>
                        <el-form-item label="是否编辑">
                            <el-switch v-model="tableConfig.isEdit"></el-switch>
                        </el-form-item>
                        <el-form-item label="是否新增">
                            <el-switch v-model="tableConfig.isCreate"></el-switch>
                        </el-form-item>
                        <el-form-item label="是否含有图片">
                            <el-switch v-model="tableConfig.isImage"></el-switch>
                        </el-form-item>
                        <el-form-item label="是否含有时间过滤">
                            <el-switch v-model="tableConfig.isTime"></el-switch>
                        </el-form-item>
                        <el-form-item label="APILIST 地址">
                            <el-input v-model="tableConfig.apiListUrl" placeholder="默认值: /api/list"></el-input>
                        </el-form-item>
                        <el-form-item label="列表数据层级">
                            <el-input v-model="tableConfig.listLevel" placeholder="默认值: res.data.main"></el-input>
                        </el-form-item>
                        <el-form-item label="APIEDIT 地址" v-if="tableConfig.isEdit">
                            <el-input v-model="tableConfig.apiEditUrl" placeholder="默认值: /api/edit"></el-input>
                        </el-form-item>
                        <el-form-item label="APICREATE 地址" v-if="tableConfig.isCreate">
                            <el-input v-model="tableConfig.apiCreateUrl" placeholder="默认值: /api/create"></el-input>
                        </el-form-item>
                    </el-form>
                    <filterConfig v-if="tableConfig.isFilter" v-model="filterData" @change="valueFilte"></filterConfig>
                    <listConfig v-model="tableData" @change="valueList"></listConfig>
                    <formConfig v-if="tableConfig.isEdit || tableConfig.isCreate" v-model="formData"
                        @change="valueForm"></formConfig>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card class="box-card" header="生成代码">
                    <el-tabs v-model="activeTab">
                        <el-tab-pane label="Vue 模板" name="template">
                            <el-input type="textarea" :rows="20" v-model="generatedTemplate" readonly></el-input>
                        </el-tab-pane>
                        <el-tab-pane label="JavaScript" name="script">
                            <el-input type="textarea" :rows="20" v-model="generatedScript" readonly></el-input>
                        </el-tab-pane>
                        <el-tab-pane label="完整代码" name="full">
                            <el-input type="textarea" :rows="20" v-model="generatedFullCode" readonly></el-input>
                        </el-tab-pane>
                    </el-tabs>

                    <el-row style="margin-top: 20px;">
                        <el-col :span="24" style="text-align: right;">
                            <el-button type="success" @click="copyCode('template')">复制模板</el-button>
                            <el-button type="success" @click="copyCode('script')">复制脚本</el-button>
                            <el-button type="success" @click="copyCode('full')">复制完整代码</el-button>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
        </el-row>


    </div>
</template>

<script>
import listConfig from './components/listConfig.vue'
import filterConfig from './components/filterConfig.vue'
import formConfig from './components/formConfig.vue'
export default {
    components: { listConfig, filterConfig, formConfig },
    data() {
        return {
            activeTab: 'full',
            tableConfig: {
                title: '',
                apiListUrl: 'list',
                listLevel: 'res.data.main',
                apiEditUrl: 'edit',
                apiCreateUrl: 'create',
                pagination: true,
                isEdit: true,
                isCreate: true,
                isFilter: true,
                isImage: true,
                isTime: true
            },
            filterData: [],
            tableData: [],
            formData: []
        }
    },
    computed: {
        generatedTemplate() {
            console.log(this.filterData, this.tableData);
            // 新增
            let createStr = ''
            if (this.tableData.isCreate) {
                createStr = `<el-button type="primary" v-if="roles.indexOf('add') != -1" icon="el-icon-circle-plus-outline" @click="handleCreate">添加</el-button>\n`
            }
            // 编辑
            let editStr = ''
            if (this.tableData.isEdit) {
                editStr = `<el-button v-if="roles.indexOf('edit') != -1" size="mini" @click="handleUpdate(row)">编辑</el-button>\n`
            }
            // 筛选
            let filterStr = ''
            if (this.filterData && this.filterData.length > 0) {
                this.filterData.forEach(item => {
                    switch (item.type) {
                        case '下拉框':
                            filterStr += `<el-select v-model="listQuery.${item.key}" placeholder="${item.name}" clearable :multiple='${item.multiple}'>\n
                            <el-option v-for="item in ${item.arrName}" :key="item.${item.idKey}" :label="item.${item.nameKey}" :value="item.${item.idKey}" />\n
                            </el-select>\n`
                            break;
                        case '时间选择':

                            break;
                        case '时间区间选择':
                            filterStr += ` <el-date-picker v-model="${item.timeArr}" type="daterange" align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="vertical-align: middle" value-format="yyyy-MM-dd HH:mm:ss" clearable :default-time="['00:00:00', '23:59:59']" :picker-options="pickerOptions" />`
                            break;
                        default:
                            filterStr += `<el-input v-model="listQuery.${item.key}" style="width: ${item.width ? item.width + 'px' : 'auto'}" placeholder="${item.name}" clearable />\n`
                            break;
                    }
                })
            }
            // 列表
            let tableDataStr = ''
            this.tableData.forEach(item => {
                switch (item.type) {
                    case 'maxtText':
                        tableDataStr += `<el-table-column :prop="${item.prop}" label="${item.label}" align="${item.align}" min-width="${item.width}"/>\n
                        <template slot-scope="{row}">\n
                           <el-tooltip class="item" effect="dark" placement="top-start" width="400" v-if="row.${item.prop} && row.${item.prop}.length > 100">\n
                           <div slot="content" style="width: 400px;">{{ row.${item.prop} }}</div>\n
                           <div class="row-text">\n
                            {{ row.${item.prop} }}\n
                           </div>\n
                           </el-tooltip>\n
                           <span v-else> {{ row.${item.prop} }}</span>\n
                        </template>\n
                        </el-table-column>\n `
                        break;
                    case 'date':
                        tableDataStr += `<el-table-column :prop="${item.prop}" label="${item.label}" align="${item.align}" min-width="${item.width}"/>\n
                        <template slot-scope="{row}">\n
                          {{ row.${item.prop} | formateDate }}\n
                        </template>\n
                        </el-table-column>\n `
                        break;
                    case 'image':
                        tableDataStr += `<el-table-column :prop="${item.prop}" label="${item.label}" align="${item.align}" min-width="${item.width}"/>\n
                        <template slot-scope="{row}">\n
                         <el-image fit="contain" style="width: auto; height: 60px;cursor: pointer;" :src="row.${item.prop}" @click="lookPic(row.${item.prop})"> </el-image>\n
                        </template>\n
                        </el-table-column>\n `
                        break;
                    case 'isID':
                        tableDataStr += `<el-table-column :prop="${item.prop}" label="${item.label}" align="${item.align}" min-width="${item.width}"/>\n
                        <template slot-scope="{row}">\n
                          {{ ${item.getFunName}(row.${item.prop}) }}\n
                        </template>\n
                        </el-table-column>\n `
                        break;
                    case 'operation':
                        tableDataStr += `<el-table-column :prop="${item.prop}" label="${item.label}" align="${item.align}" min-width="${item.width}"/>\n
                        <template slot-scope="{row}">\n
                          ${editStr}
                        </template>\n
                        </el-table-column>\n `
                        break;
                    case 'custom':
                        tableDataStr += `<el-table-column :prop="${item.prop}" label="${item.label}" align="${item.align}" min-width="${item.width}"/>\n
                        <template slot-scope="{row}">\n
                          ${item.formatter}
                        </template>\n
                        </el-table-column>\n `
                        break;
                    default:
                        tableDataStr += `<el-table-column :prop="${item.prop}" label="${item.label}" align="${item.align}" min-width="${item.width}"/>\n`
                        break;
                }
            })
            //   分页
            let paginationStr = ``
            if (this.tableConfig.pagination) {
                paginationStr = "<pagination v-show='total > 0' :total='total' :page.sync='listQuery.page' :limit.sync='listQuery.limit' @pagination='getList' />"
            }
            // 表单
            let formStr = ''
            if (this.tableConfig.isEdit || this.tableConfig.isCreate) {
                this.formData.forEach(item => {
                    switch (item.type) {
                        case '下拉框':
                            formStr += `<el-form-item label="${item.name}" prop="${item.key}">\n
                                <el-select v-model="temp.status" placeholder="${item.name}" style="width: ${item.width}px"  :multiple='${item.multiple}'>\n
                                    <el-option v-for="item in ${arrName}" :key="item.${item.idKey}" :label="item.${item.nameKey}" :value="item.${item.idKey}" />\n
                                </el-select>\n  
                            </el-form-item>\n`
                            break;
                        case '时间选择':
                            formStr += `<el-form-item label="${item.name}" prop="${item.key}">\n
                                      
                            </el-form-item>\n`
                            break;
                        case '长文本':
                            formStr += `<el-form-item label="${item.name}" prop="${item.key}">\n
                                <el-input v-model="temp.${item.key}" style="width: ${item.width}px" placeholder="${item.name}" type="textarea" :rows="${item.rows}" />\n
                            </el-form-item>\n`
                            break;
                        case '图片上传':
                            formStr += `<el-form-item label="${item.name}" prop="${item.key}">\n
                                      
                            </el-form-item>\n`
                            break;
                        case '视频上传':
                            formStr += `<el-form-item label="${item.name}" prop="${item.key}">\n
                                      
                            </el-form-item>\n`
                            break;
                        case '文件上传':
                            formStr += `<el-form-item label="${item.name}" prop="${item.key}">\n
                                      
                            </el-form-item>\n`
                            break;
                        case '富文本':
                            formStr += `<el-form-item label="${item.name}" prop="${item.key}">\n
                                      
                            </el-form-item>\n`
                            break;

                        default:
                            formStr += `<el-form-item label="${item.name}" prop="${item.key}">\n
                                   <el-input v-model="temp.${item.key}" placeholder="${item.name}" style="width: ${item.width}px" />\n    
                            </el-form-item>\n`
                            break;
                    }
                })
            }
            let isformStr = ''
            if (formStr) {
                isformStr = `<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">\n
                <el-form ref="form" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 500px;margin-left: 50px;">\n
                  ${formStr}
                </el-form>\n
                <span slot="footer" class="dialog-footer">\n
                <el-button @click="dialogFormVisible = false">取 消</el-button>\n
                <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">确 定</el-button>\n
                </span>\n
            </el-dialog>\n`
            }
            let isImage = ''
            if (this.tableConfig.isImage) {
                isImage = ` <el-dialog :visible.sync="dialogFormVisibleImg" center>\n
                 <el-image fit="contain" style="width: 400px; height: 400px;display:block;margin:0 auto"  :src="loookPicUrl" />\n
                </el-dialog>\n`
            }
            let template = ` <template>\n
              <div class="app-container">\n
              <div class="filter-container">\n
              <div class="header">\n
                ${createStr}
                ${filterStr}
               </div>\n
               </div>\n
               <el-table v-loading="listLoading" :data="list" border :header-cell-style="{ background: '#F5F7FA' }" style="width: 100%; text-align: center">\n
                ${tableDataStr}
               </el-table>\n
               ${paginationStr}\n
               ${isformStr}
               ${isImage}
               </div>\n
            </template>\n`;
            return template;
        },

        generatedScript() {
            let filtersStr = ''
            if (this.tableConfig.isTime) {
                filtersStr = `formateDate(time) {\n
                if (!time) {\n
                   return "--";\n
                }\n
                const date = new Date(time);\n
                return formateDate(date, "YYYY-MM-dd hh:mm");\n`
            }
            let dataStr = ''
            let listQueryStr = ''
            let tempStr = ''
            this.filterData.forEach(item => {
                switch (item.type) {
                    case '下拉框':
                        if (item.multiple) {
                            listQueryStr += `${item.key}:[],//${item.name}\n`
                        } else {
                            listQueryStr += `${item.key}:'',//${item.name}\n`
                        }
                        break;
                    case '时间区间选择':
                        listQueryStr += item.startKey + ":''\n" + item.endKey + ":'',\n"
                        break;
                    default:
                        listQueryStr += item.key + ":'',\n"
                        break;
                }
                let arrName = item.arrName || (item.key + 'Arr')
                if (arrName) {
                    if (item.isRequest) {
                        dataStr += `${arrName}:[],//${item.name}\n`
                    } else {
                        dataStr += `${arrName}:${item.data || '[]'},//${item.name}\n`
                    }
                }
            })
            let rulesStr = ''
            this.formData.forEach(item => {
                switch (item.type) {
                    case '下拉框':
                        rulesStr += `${item.key}: { required: ${item.required}, message: "${item.name}不能为空", trigger: "change" },\n`
                        if (item.multiple) {
                            tempStr += `${item.key}:[],//${item.name}\n`
                        } else {
                            tempStr += `${item.key}:'',//${item.name}\n`
                        }
                        break;
                    case '时间区间选择':
                        tempStr += item.startKey + ":''\n" + item.endKey + ":''\n"
                        break;
                    default:
                        tempStr += item.key + ":''"
                        break;
                }
                let arrName = item.arrName || (item.key + 'Arr')
                if (arrName) {
                    if (item.isRequest) {
                        dataStr += `${arrName}:[],//${item.name}\n`
                    } else {
                        dataStr += `${arrName}:${item.data || '[]'},//${item.name}\n`
                    }
                }
            })
            let createdStr = ''
            let methodsStr = ''
            let script = `<script>\n
            import api from "@/api/url";\n
            import Pagination from "@/components/Pagination";\n
            import { parseTime, formateDate, getDateRange } from "@/utils";\n
            import { getToken } from "@/utils/auth";\n
            export default {\n
            name: 'name',//${this.tableConfig.title}\n
            components: { Pagination },\n
            filters: {${filtersStr}},\n
            data() {\n
                return {\n
                    ${dataStr}
                    textMap: {\n
                    updata: "修改",\n
                    create: "新增",\n
                    },\n
            dialogStatus: '',\n
            list: [],\n
            total: 0,\n
            listQuery: {\n
                ${listQueryStr}
                token: getToken(),\n
                page: 1,\n
                limit: 50,\n
            },\n
            temp: {\n
                token: getToken(),\n
                ${tempStr}
            },\n
            roles: [],\n
            dialogFormVisible: false,\n
            dialogFormVisibleImg: false,\n
            rules: {\n
               ${rulesStr}
            },\n
            listLoading: false,\n
            loookPicUrl: '',\n
        }
    },\n
    watch: {},\n
    computed: {},\n
    created() {\n
        if (this.$route.meta.c != undefined) {\n
            this.$route.meta.c.forEach((element) => {\n
                this.roles.push(element.path);\n
            });\n
        }\n
        this.getDomainInfoUrl()\n
        this.getclassListType()\n
        this.handleFilter()
    },
    mounted() { },\n
    methods: {\n
        // 获取状态名\n
        getStatusName(row, column, id) {\n
            let obj = this.statusArr.find(item => item.id == id)\n
            if (obj && obj.name) {\n
                return obj.name\n
            }\n
            return ''\n
        },\n

        // 获取分类名称\n
        getClassName(id) {\n
            let obj = this.classArr.find(item => item.id == id)\n
            if (obj && obj.name) {\n
                return obj.name\n
            }\n
            return ''\n
        },\n
        // 获取分类\n
        getclassListType() {\n
            api.classList({ token: getToken(), limit: 10000 }).then(res => {\n
                if (res.code == 200) {\n
                    this.classArr = res.data.main.data\n
                }\n
            })\n
        },\n

        // 查看大图\n
        lookPic(imgUrl) {\n
            this.dialogFormVisibleImg = true;\n
            this.loookPicUrl = imgUrl;\n
        },\n
        // 默认值\n
        resetForm() {\n
            this.temp = {\n
                token: getToken(),\n
                name: '',\n
                status: '',\n
                desc: '',\n
            }\n
        },\n

        // 提交参数过滤\n
        setTemp() {\n
            let params = Object.assign({}, this.temp)\n
            return params\n
        },\n
        // 修改数据过滤\n
        setUpdate(row) {\n
            let params = Object.assign({}, row);\n
            return params\n
        },\n

        // 新增-唤起\n
        handleCreate() {\n
            this.dialogStatus = 'create'\n
            this.dialogFormVisible = true\n
            this.resetForm()\n
            this.$nextTick(() => {\n
                this.$refs["form"].clearValidate();\n
            });\n
        },\n
        // 新增-确认\n
        createData() {\n
            this.$refs["form"].validate((valid) => {\n
                if (valid) {\n
                    api.${this.tableConfig.apiCreateUrl}(this.setTemp()).then((res) => {\n
                        if (res.code == 200) {\n
                            this.$message({\n
                                message: "创建成功",\n
                                type: "success",\n
                            });\n
                            this.dialogFormVisible = false;\n
                            this.getList();\n
                        }\n
                    });\n
                } else {\n
                    return false;\n
                }\n
            });\n
        },\n
        // 修改-唤起\n
        handleUpdate(row) {\n
            this.dialogStatus = 'updata'\n
            this.dialogFormVisible = true\n
            this.temp = Object.assign({}, this.setUpdate(row));\n
            this.$nextTick(() => {\n
                this.$refs["form"].clearValidate();\n
            });\n
        },\n

        // 更新-确认\n
        updateData() {\n
            this.$refs["form"].validate((valid) => {\n
                if (valid) {\n
                    api.${this.tableConfig.apiEditUrl}(this.setTemp()).then((res) => {\n
                        if (res.code == 200) {\n
                            this.$message({\n
                                message: "修改成功",\n
                                type: "success",\n
                            });\n
                            this.dialogFormVisible = false;\n
                            this.getList();\n
                        }\n
                    });\n
                } else {\n
                    return false;\n
                }\n
            });\n
        },\n
        // 查询\n
        handleFilter() {\n
            this.getList();\n
        },\n
        // 请求列表\n
        getList() {\n
            this.listLoading = true\n
            api.${this.tableConfig.apiListUrl}(this.listQuery).then((res) => {\n
                if (res.code == 200) {\n
                    this.listLoading = false\n
                    this.total = ${this.tableConfig.listLevel}.total;\n
                    this.list = ${this.tableConfig.listLevel}.data;\n
                }\n
            }).catch(() => {\n
                this.listLoading = false\n
            });\n
        },\n
    },\n
}\n
\n
\n
<style lang="scss" scoped>\n
.row-text {\n
    display: -webkit-box;\n
    -webkit-line-clamp: 3;\n
    -webkit-box-orient: vertical;\n
    overflow: hidden;\n
    text-overflow: ellipsis;\n
}\n`;
            return script;
        },

        generatedFullCode() {
            return `${this.generatedTemplate}\n\n${this.generatedScript}`;
        }
    },
    methods: {
        valueList(value) {
            this.tableData = value
        },
        valueFilte(value) {
            this.filterData = value
        },
        valueForm(value) {
            this.formData = value
        },
        copyCode(type) {
            let textToCopy = '';
            let message = '';

            switch (type) {
                case 'template':
                    textToCopy = this.generatedTemplate;
                    message = '模板代码复制成功!';
                    break;
                case 'script':
                    textToCopy = this.generatedScript;
                    message = '脚本代码复制成功!';
                    break;
                case 'full':
                    textToCopy = this.generatedFullCode;
                    message = '完整代码复制成功!';
                    break;
            }

            this.copyToClipboard(textToCopy).then(() => {
                this.$message({
                    type: 'success',
                    message: message
                });
            }).catch(err => {
                this.$message({
                    type: 'error',
                    message: '复制失败，请手动复制'
                });
                console.error('复制失败:', err);
            });
        },

        copyToClipboard(text) {
            return navigator.clipboard.writeText(text);
        },

        handleRowClick(row) {
            // 点击行时编辑列
            const index = this.tableData.findIndex(column => column.prop === row.prop);
            if (index > -1) {
                this.editColumn(index, row);
            }
        },
    }
}
</script>

<style scoped>
.box-card {
    min-height: 600px;
}

.el-table {
    margin-top: 20px;
}

.dialog-footer {
    text-align: right;
}

.copy-button {
    margin-left: 10px;
}
</style>